import SwiftUI
import Combine

class TimerViewModel: ObservableObject {
    @Published var timeString: String = "00:00:00"
    
    private var timer: DispatchSourceTimer?
    private var startTime: Date?
    
    func start() {
        stop()
        
        startTime = Date()
        
        let queue = DispatchQueue(label: "TimerQueue")
        timer = DispatchSource.makeTimerSource(queue: queue)
        timer?.schedule(deadline: .now(), repeating: .seconds(1))
        timer?.setEventHandler { [weak self] in
            self?.updateTime()
        }
        timer?.resume()
    }
    
    func stop() {
        timer?.cancel()
        timer = nil
        // Reset time when stopping
        timeString = "00:00:00"
        startTime = nil
    }
    
    private func updateTime() {
        guard let startTime = startTime else { return }
        
        let now = Date()
        let elapsedTime = now.timeIntervalSince(startTime)
        let hours = Int(elapsedTime) / 3600
        let minutes = (Int(elapsedTime) % 3600) / 60
        let seconds = Int(elapsedTime) % 60
        
        // Ensure UI updates happen on the main thread
        DispatchQueue.main.async {
            self.timeString = String(format: "%02d:%02d:%02d", hours, minutes, seconds)
        }
    }
}
